package leetcode;

import java.util.*;

/**
 * 找出前k个高频数据
 * https://leetcode-cn.com/problems/top-k-frequent-elements/
 */
public class T347 {

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num,Optional.ofNullable(map.get(num)).orElse(0)+1);
        }
        int[] ints = map.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry<Integer,Integer>::getValue).reversed())
//                .sorted(Comparator.comparing(Map.Entry::getValue).reversed()) //不太清楚这种写法为啥无法自动推断泛型类型
                .map(t -> t.getKey())
                .limit(k)
                .mapToInt(Integer::intValue).toArray();

        return ints;
    }

    public static void main(String[] args) {
//        int[] nums = {1,1,1,2,2,3};
        int[] nums = {4,1,-1,2,-1,2,3};
        int k = 2;

        T347 t347 = new T347();
        int[] ints = t347.topKFrequent(nums, k);
        System.out.println(Arrays.toString(ints));
    }
}
